// index/index3.js
const app = getApp()
const api = require('../fetch/api')
const { baseURL,ip } = require('../fetch/http')
Component({
  /**
   * 组件的属性列表
   */
  pageLifetimes: {
    show() {
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          selected: 1
        })
      }

      // 获取分享页面的用户id参数 用于注册生成上下级关系
      const pages = getCurrentPages()
      const currentPage = pages[pages.length-1]
      let { id, scene } = currentPage.options
      console.log(currentPage.options);
      if(id) {
        wx.setStorageSync('recommend', id)
      }
      if(scene) {
        wx.setStorageSync('recommend', scene)
      }

      app.authTo(async ()=>{
        this.clear();
        await this.classify()
        this.goods()
      })
    },
  },
  lifetimes: {
    attached() {

    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    tabs: [],
    tabIndex: 0,
    toView: 's0',
    goods_classify_id: '',
    arr: [],
    loading: false,
    finished: false,
    page: 1
  },

  /**
   * 组件的方法列表
   */
   methods: {
    async classify() {
      let res = await api.goodsClassify()
      this.setData({
        tabs: res.data,
        goods_classify_id: res.data[0].id
      })
    },
    detail(e) {
      const { id } = app.dataSet(e)
      wx.navigateTo({
        url: '/pages/my/integralGoods/index?id=' + id,
      })
    },
    switchTab(e) {
      const { index } = app.dataSet(e)
      if (this.data.tabIndex != index) {
        this.setData({
          tabIndex: index,
          goods_classify_id: this.data.tabs[index].id,
          toView: 's' + index
        })
        this.clear()
        this.goods()
      }
    },  
    clear() {
      this.setData({
        page: 1,
        loading: false,
        finished: false,
        arr: []
      })
    },
    async goods() {
      if (!this.data.loading) {
        this.setData({
          loading: true
        })
        let res = await api.goods({
          page: this.data.page,
          goods_type: 2,
          goods_classify_id: this.data.goods_classify_id
        })
        let finished = false
        res.data.length == 0 && (finished = true)
        this.setData({
          arr: [...this.data.arr,...res.data],
          finished,
          loading: false
        })
      }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad (options) {
      await this.classify()
      this.goods()
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
      let {
        page,
        finished
      } = this.data
      if (!finished) {
        this.setData({
          page: page + 1
        })
        this.goods()
      }
    },
  
  }
})
